package com.heaven.back.controller;

import com.alibaba.fastjson.JSONObject;
import com.heaven.back.pojo.*;
import com.heaven.back.service.ActionService;
import com.heaven.back.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * The type Login controller.
 */
@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class LoginController {
    @Autowired
    private ActionService actionService;


    /**
     * Login result.
     *
     * @param p the p
     * @return the result
     */
    @PostMapping("/login")
    public Result login(@RequestBody Player p) {
        //先查找
        Player e = actionService.Login(p);
        //已有用户
        if (e != null) {

            if (e.isLogin()) {
                return Result.error("该用户已登陆");
            }

            //return Result.success(e);
            e.set_items((JSONObject.parseArray(e.getItems(), Item.class)));
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            claims.put("name", e.getName());
            claims.put("room", e.getCurrentRoom());
            String jwt = JwtUtils.generateJwt(claims);//jwt包含了当前登录的员工信息

            e.setIslogin(1);
            actionService.update(e);

            return Result.success(new LoginMsg(jwt, e));
        }
        return Result.error("用户名或密码错误");
    }

}
